// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 获取status为1的投票活动
    const voteResult = await db.collection('vote_activity')
      .where({ status: 1 })
      .orderBy('_createTime', 'desc')
      .get()

    if (!voteResult.data || voteResult.data.length === 0) {
      return {
        success: true,
        data: [],
        message: '暂无投票活动'
      }
    }

    // 为每个投票活动计算统计信息
    const voteListWithStats = await Promise.all(
      voteResult.data.map(async (vote) => {
        try {
          // 计算总投票数
          const totalVoteResult = await db.collection('vote_record')
            .where({
              _voteId: vote._id
            })
            .count()

          // 计算每个选项的票数
          const optionsWithVotes = await Promise.all(
            (vote.options || []).map(async (option, index) => {
              const optionVoteResult = await db.collection('vote_record')
                .where({
                  _voteId: vote._id,
                  option: index
                })
                .count()

              return {
                ...option,
                votes: optionVoteResult.total || 0
              }
            })
          )

          // 按票数排序选项
          const sortedOptions = optionsWithVotes.sort((a, b) => b.votes - a.votes)

          return {
            ...vote,
            totalVotes: totalVoteResult.total || 0,
            options: sortedOptions,
            // 确保背景图片字段存在
            backgroundImage: vote.backgroundImage || ''
          }
        } catch (error) {
          console.error(`处理投票 ${vote._id} 时出错:`, error)
          return {
            ...vote,
            totalVotes: 0,
            options: vote.options || [],
            backgroundImage: vote.backgroundImage || ''
          }
        }
      })
    )

    return {
      success: true,
      data: voteListWithStats,
      message: '获取投票列表成功'
    }

  } catch (error) {
    console.error('获取投票列表失败:', error)
    return {
      success: false,
      message: '获取投票列表失败',
      error: error.message,
      data: []
    }
  }
}